package work.comeback.omo.service.imp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.dao.movie.IMovieDetail;
import work.comeback.omo.dao.movie.IMovieInfo;
import work.comeback.omo.dao.movie.imp.MovieDetailImpl;
import work.comeback.omo.dao.movie.imp.MovieInfoImpl;
import work.comeback.omo.service.MovieService;
import work.comeback.omo.util.configuration.Application;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class MovieServiceImpl implements MovieService {
    private static final Logger logger = LoggerFactory.getLogger(MovieServiceImpl.class);
    private static final Application application = Application.getInstance();
    private final Connection connection;

    public MovieServiceImpl() {
        this(application.getConnection());
    }

    public MovieServiceImpl(Connection connection) {
        this.connection = connection;
        initializeTables();
    }

    private void initializeTables() {
        try (Statement stmt = connection.createStatement()) {
            createTableIfNotExists(stmt, "movie_info", "vod_id INT PRIMARY KEY, vod_name VARCHAR(255), type_name VARCHAR(255), vod_time VARCHAR(255), vod_remarks VARCHAR(255)");
            createTableIfNotExists(stmt, "movie_detail", "vod_id INT PRIMARY KEY, vod_name VARCHAR(255), vod_en VARCHAR(255), vod_tag VARCHAR(255), vod_pic VARCHAR(255), vod_blurb TEXT, vod_remarks VARCHAR(255), vod_year VARCHAR(255), vod_duration VARCHAR(255), vod_time VARCHAR(255), vod_content TEXT, vod_play_url TEXT");
        } catch (SQLException e) {
            logger.error("Error initializing tables", e);
        }
    }

    private void createTableIfNotExists(Statement stmt, String tableName, String columns) throws SQLException {
        String checkTableSQL = "SELECT 1 FROM " + tableName + " LIMIT 1";
        try {
            stmt.executeQuery(checkTableSQL);
        } catch (SQLException e) {
            logger.info("{} table does not exist, creating...", tableName);
            String createTableSQL = "CREATE TABLE " + tableName + " (" + columns + ")";
            stmt.executeUpdate(createTableSQL);
            logger.info("{} table created successfully", tableName);
        }
    }

    @Override
    public IMovieDetail getMovieDetail() {
        return new MovieDetailImpl(connection);
    }

    @Override
    public IMovieInfo getMovieInfo() {
        return new MovieInfoImpl(connection);
    }
}
